package com.vip.mvc.demo.controller;

import com.vip.mvc.akka.Promises;
import com.vip.mvc.annotation.Async;
import com.vip.mvc.annotation.Autowired;
import com.vip.mvc.annotation.Controller;
import com.vip.mvc.annotation.PathVariable;
import com.vip.mvc.annotation.RequestBody;
import com.vip.mvc.annotation.RequestMapping;
import com.vip.mvc.annotation.RequestMethod;
import com.vip.mvc.annotation.ResponseBody;
import com.vip.mvc.demo.msg.DemoReq;
import com.vip.mvc.demo.service.DemoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.concurrent.Future;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by cloudy.xie on 17/2/14.
 */
@Controller
public class DemoController {
    private Logger logger = LoggerFactory.getLogger(DemoController.class);

    @ResponseBody
    @RequestMapping(value = "/testJson", method = RequestMethod.GET)
    public void testJson(@PathVariable("id") int id) {
        logger.info("testJson-id=" + id);
    }

    @ResponseBody
    @RequestMapping(value = "/testJson2", method = RequestMethod.POST)
    public Map testJson2(@PathVariable("no") int no, @RequestBody DemoReq demoReq) {
        Map<String, String> returnMap = new HashMap<>();
        returnMap.put("one", "testONe");
        returnMap.put("two", "testONe2");
        returnMap.put("one2", "testONe3");
        returnMap.put("no", String.valueOf(no));
        returnMap.put("id", String.valueOf(demoReq.getId()));
        returnMap.put("name", demoReq.getName());
        return returnMap;
    }

    @Async
    @ResponseBody
    @RequestMapping(value = "/asyncTask", method = RequestMethod.POST)
    public Future<Object> asyncTask(@RequestBody DemoReq demoReq) throws IOException {
        return Promises.flatMap(demoReq, req -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Map<String, String> returnMap = new HashMap<>();
            returnMap.put("async", "async ++++++++++++++");
            returnMap.put("one", "testONe");
            returnMap.put("two", "testONe2");
            returnMap.put("one2", "testONe3");
            returnMap.put("id", String.valueOf(req.getId()));
            returnMap.put("name", req.getName());
            return returnMap;
        });
    }

    @Async
    @ResponseBody
    @RequestMapping(value = "/testParam", method = RequestMethod.POST)
    public Future<Object> testParam(@RequestBody DemoReq demoReq) throws IOException {
        logger.info("controller thread ="+Thread.currentThread().getName());
        return demoService.testService(demoReq);
    }

    @Autowired
    private DemoService demoService;

    public DemoService getDemoService() {
        return demoService;
    }
}
